

$(document).ready(function(){BBMain.Init(); });

var LaneSchedule;
var LaneEditView;
var LaneList;
var LaneListView;

var BBMain = {
	
	ls1: {},	
	allLanes: {},
	laneClosure_view: {},
	laneList_view: {},
		
	Init: function(){
		
		// Init screen
		$('#btnCheckSpeed').on('click', this.CheckSpeed);
		$('#btnGetList').on('click', this.LoadList);
		
		_.templateSettings = {
    		    interpolate: /\<\@\=(.+?)\@\>/gim,
    		    evaluate: /\<\@(.+?)\@\>/gim,
    		    escape: /\<\@\-(.+?)\@\>/gim
    		};
		
		// Init model
		LaneSchedule = Backbone.Model.extend({
			
			url: 'save',
	        defaults: {
	        	speedLimit: 85, 
	        	measures: [ "cones" ]
	        },
			
			validate: function( attributes ){
				
				var start = parseInt(attributes.start);
				var end = parseInt(attributes.end);
				
				var errors = [];
				
	            if( start < 0 ){
	            	errors.push({ name: "start", message: "time can't be < 0"} );
	            }
	            
	            if( end < 0 ){
	            	errors.push({ name: "end", message: "time can't be < 0"} );
	            }
	            
	            if( start > 24 ){
	            	errors.push({ name: "start", message: "time can't be > 24"} );
	            }
	            
	            if( end > 24)
	            {
	            	errors.push({ name: "end", message: "time can't be > 24"} );
	            }
	            
	            if( start > end){
	            	errors.push({ name: "start", message: "start must be before end"} );
	            	errors.push({ name: "end", message: "start must be before end"} );
	            }
	            
	            if(errors.length > 0) return errors;
	        },
			
			initialize: function(){
				Utils.AppendText('#txtOutput','LaneSchedule initialized');
				
				this.on("change:lane", function(model){
	                var name = model.get("lane"); 
	                alert("Lane name changed to " + name );
	            });

				this.bind("error", function(model, errors){
	                // We have received an error, log it, alert it or forget it :)
					for (var i = 0; i < errors.length; ++i) {
						Utils.MarkInvalid(errors[i].name, this.view);
			        }
	            });
			}
		});
		
		LaneList = Backbone.Collection.extend({
			model: LaneSchedule,
			url: "getList"
		});
		
		// Views
		LaneEditView = Backbone.View.extend({
			initialize: function(){
				this.render();
	        },
	        
	        render: function(){
	        	
	            // Compile the template using underscore
	        	this.model.view = this.$el;
	            var template = _.template( $("#lane_edit_template").html(), this.model.attributes );
	            // Load the compiled HTML into the Backbone "el"
	            this.$el.html( template );
	        },
	        
	        events: {
	            "click input[name=btnSave]": "doSave"  
	        },
	        
	        doSave: function( event ){
	        	
	        	var obj = this.$el.ToObject();
	        	//var obj = this.$el.serializeObject();
	        	Utils.ClearInvalid(this.$el);
	        	
	        	this.model.set(obj,{silent: true});
	        	
	        	if(this.model.isValid()){
		        	this.model.save({}, {
		    			success: BBMain.saveSuccess, 
		    			error: BBMain.saveFail,
		    			dataType: "json",
		    			headers: { 
		    		        'Accept': 'application/json',
		    		        'Content-Type': 'application/json' 
		    		    }
		        	});
	        	} else {
	        		var errors = this.model.validate(this.model.attributes);
	        		for (var i = 0; i < errors.length; ++i) {
						Utils.MarkInvalid(errors[i].name, errors[i].message, this.$el);
			        }
	        	}
	        }
		}); 

		LaneListView = Backbone.View.extend({
			initialize: function(){
				this.render();
	        },
	        
	        render: function(){
	    		var template = _.template( $("#lane_list_template").html(), { lanes: this.model.models } );
	            this.$el.html( template );
	        }
		}); 
		
		// Set up random stuff for display in the view
		this.ls1 = new LaneSchedule({ lane: "A", start: 3, end: 12});
		this.ls1.set({ speedLimit: 50, measures: [ "cones" ] });
		
		this.allLanes = new LaneList();
		
		this.laneClosure_view = new LaneEditView({ model: this.ls1,  el: $("#laneEditSection") });
		this.laneList_view = new LaneListView({ model: this.allLanes,  el: $("#laneListSection") });
	},
		
	CheckSpeed: function(){
		//alert(BBMain.ls1.get("speedLimit"));
		alert(BBMain.ls1.toJSON());
	},
	
	/// List section
	LoadList: function(){
		BBMain.allLanes.fetch({
			success: BBMain.loadListSuccess, 
			error: BBMain.loadListFail,
			dataType: "json",
			headers: { 
		        'Accept': 'application/json',
		        'Content-Type': 'application/json' 
		    }
		});
	},
	
	loadListFail: function(collection, xhr, options){
		alert("List load failed: " + xhr.statusText);
	},
	
	loadListSuccess: function(collection, response, options){
		BBMain.laneList_view.render();
	},

	// Save handlers
	saveFail: function(model, xhr, options){
		alert("Save failed: " + xhr.statusText);
	},
	
	saveSuccess: function(model, response, options){
		BBMain.ls1.clear({silent: true}); 
		BBMain.ls1.set({ lane: "", start: "", end: ""});
		BBMain.laneClosure_view.render();
		BBMain.LoadList(); // refresh the list
	}
	
};